package com.example.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.test.entity.Order;
import com.example.test.service.OrderService;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping
    public List<Order> getAllOrders() {
        return orderService.getAllOrders();
    }

    @GetMapping("/{id}")
    public Order getOrderById(@PathVariable Long id) {
        return orderService.getOrderById(id);
    }

    @PostMapping
    public Order createOrder(@RequestBody Order order) {
        return orderService.createOrder(order);
    }

    @PostMapping("/{orderId}/cancel")
    public void cancelOrder(@PathVariable Long orderId, @RequestBody Map<String, String> request) {
        String reason = request.get("reason");
        orderService.cancelOrder(orderId, reason);
    }

    @PostMapping("/{orderId}/refund")
    public void requestRefund(@PathVariable Long orderId, @RequestBody Map<String, String> request) {
        String reason = request.get("reason");
        orderService.requestRefund(orderId, reason);
    }

    @PostMapping("/{orderId}/reviews/{productId}")
    public void submitReview(@PathVariable Long orderId, @PathVariable Long productId, @RequestBody Map<String, String> request) {
        String review = request.get("review");
        String username = request.get("username");
        orderService.submitReview(orderId, productId, review,username);
    }

    @PostMapping("/updateStatus")
    public void updateOrderStatus(@RequestBody Map<String, Object> request) {
        Long orderId = ((Number) request.get("orderId")).longValue();
        String status = (String) request.get("status");
        orderService.updateOrderStatus(orderId, status);
        if ("退款成功".equals(status)) {
            orderService.updateProductInventory(orderId, status);
        }
    }

    @GetMapping("/refund-requests")
    public List<Order> getRefundRequests() {
        return orderService.getRefundRequests();
    }

    @GetMapping("/reviews/pending")
    public List<Map<String, Object>> getPendingReviews() {
        return orderService.getPendingReviews();
    }

    @PostMapping("/reviews/update")
    public void updateReviewStatus(@RequestBody Map<String, Object> request) {
        Long reviewId = ((Number) request.get("reviewId")).longValue();
        boolean iflegal = (Boolean) request.get("iflegal");
        orderService.updateReviewStatus(reviewId, iflegal);
    }

}